import React,{Component} from 'react';
import {List, Avatar} from 'antd';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import data from './data';
import TxtTag from '../txtTag';
import axios from 'axios';
import {getListData} from '../../actions/list';
class IndexList extends Component{
	constructor(props){
		super(props);
		let {loading,data} = this.props;
		this.state = {
			page: 1,
			loading,
			data
		}
		//console.log('props',this.props);
		this.props.dispatch(getListData([], this.props.tab, 1))
		//this.getData(this.props.tab);
	}
	//componentWillReceiveProps(nextProps){
	shouldComponentUpdate(nextProps,nextState){
		console.log(nextProps)
		if(this.state.page !== nextState.page){
			this.props.dispatch(getListData(this.props.data , nextProps.tab, nextState.page))
		}
		if(this.props.tab !== nextProps.tab){
			//this.getData(nextProps.tab);
			this.state.page = 1;
			this.props.dispatch(getListData(this.props.data , nextProps.tab, 1))
			return false;
		}
		return true;
	}
	getData(tab){
		this.props.dispatch((dispatch)=>{
			dispatch({
				type:'LIST_UPDATE',
			})
			axios.get(`https://cnodejs.org/api/v1/topics?tab=${tab}&page=${this.state.page}&limit=10`)
			.then(res=>{
				console.log(res);
				dispatch({
					type:'LIST_UPDATE_SUCC',
					data:res.data
				})
			})
			.catch(error=>{
				//console.log(error)
				dispatch({
					type:'LIST_UPDATE_ERROR',
					data:error
				})
			})
		})
	}
	render(){
		//console.log('list props',this.props);
		let {data,loading} = this.props;
		let pagination = {
			current : this.state.page,
			pageSize: 10,
			total: 1000,
			onChange: ((current)=>{
				this.setState({
					page: current
				})
			})
		}
		return(
			<div>
			<List loading={loading}
				dataSource={data}
				pagination={(loading || data.length == 0)?false:pagination}
				renderItem = {item => (
					<List.Item actions={['回复'+item.reply_count,'访问'+item.visit_count]}>
						<List.Item.Meta
							avatar={<Avatar src={item.author.avatar_url}/>}
							title={<div><TxtTag data={item}/>
								<Link to={"/details/"+item.id}>{item.title}</Link>
								</div>
							}
							description={<p>
								<Link to={"/user/"+item.author.loginname}>{item.author.loginname}</Link>
								发表于：{item.create_at.split('T')[0]}
							</p>}
						/>
					</List.Item>)}
				>

			</List>
			
			</div>
		)
	}
}
export default connect(state=>state.list)(IndexList);